package com.sgb.kjwl.view.ui.activity.packers;

import android.content.Context;
import android.content.Intent;
import android.text.TextUtils;
import android.util.SparseArray;
import android.util.SparseIntArray;
import android.view.View;

import androidx.core.content.ContextCompat;
import androidx.databinding.DataBindingUtil;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.sgb.kjwl.AppActivity;
import com.sgb.kjwl.R;
import com.sgb.kjwl.databinding.AtPackersEngineeringTenderBinding;
import com.sgb.kjwl.model.entity.TenderListEntity;
import com.sgb.kjwl.model.entity.packers.PickResultEntity;
import com.sgb.kjwl.model.entity.user.AddressEntity;
import com.sgb.kjwl.view.ui.activity.WebViewX5HostActivity;
import com.sgb.kjwl.view.ui.activity.pick.TenderDetailsActivity3;
import com.sgb.kjwl.view.ui.adapter.packers.PackerHallBidingAdapter;
import com.sgb.kjwl.view.widget.PickPopWindow1;
import com.sgb.kjwl.view.widget.ThreeLevelAreaWindow;
import com.sgb.kjwl.view.widget.ThreeLevelFilterWindow;
import com.sgb.kjwl.view.widget.pick.PickChooseLeftDialog2;
import com.sgb.kjwl.viewmodel.packers.PackersEngineeringTenderModel;
import com.sgb.kjwl.viewmodel.quotedprice.QuotedPriceModel;
import com.sgb.link.entity.PickFilterEntity;
import com.sgb.link.utils.PickCateType;
import com.sgb.zhaocai.utils.PickCopyUtils;
import com.swgk.core.base.di.AppComponent;
import com.swgk.core.recyclerview.adapter.AdapterOnItemClick;
import com.swgk.core.recyclerview.entity.BaseAreaEntity;
import com.swgk.core.util.PickSelectEntity;
import com.swgk.core.util.PickSelectTextEntity;
import com.swgk.core.xrecyclerview.XRecyclerView;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * @author liwei
 * @date 2021/4/8
 * description:工程分包列表页
 */
@Deprecated
public class PackersEngineeringTenderActivity extends AppActivity implements PickChooseLeftDialog2.DialogCallBackImpl{

    PackersEngineeringTenderModel viewModel;
    private AtPackersEngineeringTenderBinding binding;
    private PackerHallBidingAdapter adapter;

    /**
     * 工程分类
     */
    private ThreeLevelFilterWindow popCategory;
    private PickResultEntity pickResultProject1;
    private PickResultEntity pickResultProject2;
    private PickResultEntity pickResultProject3;
    private String projectName = "";
    private String projectNo = "";
    /**
     * 概算金额
     */
    private String priceNo = "";
    /**
     * 报名结束时间
     */
    private String timeNo = "";
    /**
     * 招标方式
     */
    private PickPopWindow1 popTenderMethod;
    private PickResultEntity pickResultTenderMethod;
    /**
     * 所在区域
     */
    private ThreeLevelAreaWindow popCity;
    private PickResultEntity pickResultProvince;
    private PickResultEntity pickResultCity;
    private PickResultEntity pickResultArea;
    private String areaName = "";
    private AddressEntity mAddress;

    public static void start(Context context) {
        Intent intent = new Intent();
        intent.setClass(context, PackersEngineeringTenderActivity.class);
        context.startActivity(intent);
    }

    @Override
    protected void setupActivityComponent(AppComponent appComponent) {
//        DaggerPackersComponent.builder().appComponent(appComponent).
//                packersModule(new PackersModule(this)).build().
//                inject(this);
    }

    @Override
    protected boolean statusBarDark() {
        return false;
    }

    private void initFilterData(boolean isLoadMore) {
        viewModel.getNewList(projectNo, priceNo, timeNo, pickResultTenderMethod.getNo(),
                pickResultProvince.getNo(), pickResultCity.getNo(), isLoadMore);
    }

    @Override
    protected void initView() {
        binding = DataBindingUtil.setContentView(this, R.layout.at_packers_engineering_tender);
        viewModel = new ViewModelProvider(this).get(PackersEngineeringTenderModel.class);

        binding.tvMore.setOnClickListener(this);

        if (adapter == null) {
            adapter = new PackerHallBidingAdapter(getActivity(), null);
        }

        DividerItemDecoration divider = new DividerItemDecoration(this, DividerItemDecoration.VERTICAL);
        divider.setDrawable(Objects.requireNonNull(ContextCompat.getDrawable(this, R.drawable.shape_list_divide2)));
        binding.recyclerView.addItemDecoration(divider);
        LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
        binding.recyclerView.setLayoutManager(layoutManager);
        binding.recyclerView.setAdapter(adapter);
        binding.recyclerView.setLoadingMoreEnabled(true);
        binding.recyclerView.setLoadingListener(new XRecyclerView.LoadingListener() {
            @Override
            public void onRefresh() {
                initFilterData(false);
            }

            @Override
            public void onLoadMore() {
                initFilterData(true);
            }
        });
        adapter.setOnItemClick(new AdapterOnItemClick<TenderListEntity>() {
            @Override
            public void onItemClick(TenderListEntity tenderListEntity, int position) {
                TenderDetailsActivity3.start(getActivity(), tenderListEntity.getId(), 0);
            }
        });
        adapter.onIChildClick(tenderListEntity -> TenderDetailsActivity3.start(getActivity(), tenderListEntity.getId(), 0));

        pickResultProject1 = new PickResultEntity();
        pickResultProject2 = new PickResultEntity();
        pickResultProject3 = new PickResultEntity();
        pickResultTenderMethod = new PickResultEntity();
        pickResultProvince = new PickResultEntity();
        pickResultCity = new PickResultEntity();
        pickResultArea = new PickResultEntity();


    }

    @Override
    protected void init() {
        mAddress = (AddressEntity) getIntent().getSerializableExtra("entity");
        if (mAddress != null){
            pickResultProject1.setNo((mAddress).getNo());
            pickResultProject1.setName((mAddress).getName());
            projectNo=pickResultProject1.getNo();
        }
        initFilterData(false);

        initChooseDialog();

        viewModel.getTenderGoodsCategoryAllList();
//        viewModel.getProvinceData();
        viewModel.getPriceData();
        viewModel.getPickTimes();
        viewModel.getTenderNewTypeList();
    }

    @Override
    public void onMultiClick(View v) {
        super.onMultiClick(v);
        int id = v.getId();
        if (id == R.id.iv_back) {
            finish();
        } else if (id == R.id.tv_project) {
            if (popCategory == null) {
                viewModel.getTenderProjectList();
            } else {
                showCategoryPop(null);
            }
        } else if (id == R.id.tv_area) {
            if (popCity == null) {
                viewModel.getCityList();
            } else {
                showCityPop(null);
            }
        } else if (id == R.id.tv_more) {
            mLeftDialog2.initCategory(2, false, false);
            mLeftDialog2.initData(mData, mFilters);
            mLeftDialog2.showDialog();
        }
    }

    public void showList(List<TenderListEntity> list, boolean isLoadMore, boolean isLast) {
        if (isLoadMore) {
            binding.recyclerView.loadMoreComplete();
            if (list != null && list.size() > 0) {
                adapter.addDatas(list);
            }
            binding.recyclerView.setNoMore(isLast);
        } else {
            binding.recyclerView.refreshComplete();
            if (list != null && list.size() > 0) {
                binding.emptyView.setVisibility(View.GONE);
                adapter.setDatas(list);
                binding.recyclerView.smoothScrollToPosition(0);
            } else {
                adapter.clearDatas();
                binding.emptyView.setVisibility(View.VISIBLE);
            }
        }
    }

    /**
     * 工程-工程分类
     * @param data 工程分类pop的列表数据
     */
    public void showCategoryPop(List<PickFilterEntity<List<PickFilterEntity<List<PickFilterEntity>>>>> data) {
        if (popCategory == null) {
            popCategory = new ThreeLevelFilterWindow(getActivity());
            popCategory.setBgView(binding.grayLayout);
            if (mAddress != null){
                int position = 0;
                for (int i = 0; i < data.size(); i++) {
                    if (mAddress.getNo().equals(data.get(i).getNo())){
                        position = i;
                        break;
                    }
                }
                popCategory.setDefaultItem(position);
            }

            popCategory.setOnResultClick(new ThreeLevelFilterWindow.OnResultClick() {
                @Override
                public void result(Object key1, Object key2, Object key3) {
                    pickResultProject1.setNo(((PickResultEntity) key1).getNo());
                    pickResultProject1.setName(((PickResultEntity) key1).getName());
                    pickResultProject2.setNo(((PickResultEntity) key2).getNo());
                    pickResultProject2.setName(((PickResultEntity) key2).getName());
                    pickResultProject3.setNo(((PickResultEntity) key3).getNo());
                    pickResultProject3.setName(((PickResultEntity) key3).getName());
                    initFilterData(false);
                }

                @Override
                public void reset() {
                    pickResultProject1.clear();
                    pickResultProject2.clear();
                    pickResultProject3.clear();
                    projectNo = "";
                    initFilterData(false);
                }
            });
            popCategory.setOnDismissListener(() -> {

            });
            popCategory.setThreeLevelData1(data);
        }

    }

    /**
     * 招标方式
     * @param data 招标方式pop的列表数据
     */
    public void showTenderMethodPopWindow(List<PickSelectEntity> data) {
        if (popTenderMethod == null) {
            popTenderMethod = new PickPopWindow1(this);
            popTenderMethod.setBgView(binding.grayLayout);
            popTenderMethod.setOnResultClick((PickPopWindow1.OnResultClick) (key1, key2, key3) -> {
                pickResultTenderMethod.setNo((String) key1);
                pickResultTenderMethod.setName((String) key2);
                pickResultTenderMethod.setPosition((int) key3);

                initFilterData(false);
            });
            popTenderMethod.setOnDismissListener(() -> {

            });

            popTenderMethod.setData(data);
        }

    }

    /**
     * 省市区pop
     * @param data 地区选择的列表数据
     */
    public void showCityPop(List<AddressEntity<List<AddressEntity<List<AddressEntity>>>>> data) {
        if (popCity == null) {
            popCity = new ThreeLevelAreaWindow(getActivity()){
                @Override
                protected void provinceClick(BaseAreaEntity baseAreaEntity, int position) {
                    super.provinceClick(baseAreaEntity, position);
                    pickResultProvince.setNo(baseAreaEntity.getNo());
                    pickResultProvince.setName(baseAreaEntity.getSimpleName());
                    if ("全部".equals(baseAreaEntity.getSimpleName()) || pickResultProvince.getName().equals(baseAreaEntity.getSimpleName())){
                        pickResultCity.setNo("");
                        pickResultCity.setName("");
                    }
                }

                @Override
                protected void cityClick(BaseAreaEntity baseAreaEntity, int position) {
                    super.cityClick(baseAreaEntity, position);
                    pickResultCity.setNo(baseAreaEntity.getNo());
                    pickResultCity.setName(baseAreaEntity.getSimpleName());
                    if ("全部".equals(baseAreaEntity.getSimpleName()) || pickResultCity.getName().equals(baseAreaEntity.getSimpleName())){
                        pickResultArea.setNo("");
                        pickResultArea.setName("");
                    }
                }

                @Override
                protected void areaClick(BaseAreaEntity baseAreaEntity, int position) {
                    super.areaClick(baseAreaEntity, position);
                    pickResultArea.setNo(baseAreaEntity.getNo());
                    pickResultArea.setName(baseAreaEntity.getSimpleName());
                }
            };
            popCity.setBgView(binding.grayLayout);
            popCity.setProvinceSingle();
            popCity.setCitySingle();
            popCity.setAreaSingle();
            popCity.setShowSimpleName(true);
            popCity.setThreeListIsGone(true);

            popCity.setOnResultClick((key1, key2, key3) -> {
                initFilterData(false);
            });
            popCity.setOnDismissListener(() -> {

            });
        }
    }


    /**
     * 更多筛选
     */
    private PickChooseLeftDialog2 mLeftDialog2;

    private final List<PickSelectEntity<List<PickSelectEntity<List<PickSelectEntity>>>>> categoryData = new ArrayList<>();
    /**
     * 数据集
     */
    private SparseArray<PickSelectTextEntity> mData = new SparseArray<>();
    private SparseIntArray mFilters = new SparseIntArray();
    private final SparseArray<String> nameArray = new SparseArray<>();

    private void initChooseDialog() {
        nameArray.put(PickCateType.TYPE_CATEGORY_0, "类别");
        nameArray.put(PickCateType.TYPE_CATEGORY_1, "类别1");
        nameArray.put(PickCateType.TYPE_CATEGORY_2, "类别2");
        nameArray.put(PickCateType.TYPE_SIGN, "招标方式");
        nameArray.put(PickCateType.TYPE_MONEY, "概算金额");
        nameArray.put(PickCateType.TYPE_SIGN_TIME, "报名结束时间");
        nameArray.put(PickCateType.TYPE_PROVINCE, "省份");
        nameArray.put(PickCateType.TYPE_CITY, "市区");
        nameArray.put(PickCateType.TYPE_DISTANCE, "距离");
        mLeftDialog2 = new PickChooseLeftDialog2(this, nameArray);
        mLeftDialog2.setCallBack(this);
    }

    /**
     * 添加数据到中数据聚合
     */
    private void refreshDataInfo(int sort, List<PickSelectEntity> children) {
        clearOtherDataInfo(sort);
        addEntity(sort, children);
    }

    @Override
    public void loadCategory(PickSelectTextEntity entity, int itemPos) {
        List<PickSelectEntity> children = new ArrayList<>();
        if (itemPos > 0) {
            switch (entity.getSort()) {
                case PickCateType.TYPE_CATEGORY_0:
                    if (categoryData == null || categoryData.size() == 0) {
                        return;
                    }
                    List<PickSelectEntity<List<PickSelectEntity>>> cate1 = categoryData.get(itemPos).getChildren();
                    if (cate1 != null && cate1.size() > 0) {
                        children.addAll(cate1);
                    }
                    mLeftDialog2.clearOtherDataInfo(entity.getSort());
                    mLeftDialog2.addEntity(PickCateType.TYPE_CATEGORY_1, children);
                    mLeftDialog2.showDialog();
                    break;
                case PickCateType.TYPE_CATEGORY_1:
                    if (categoryData == null || categoryData.size() == 0) {
                        return;
                    }
                    int firPos = mLeftDialog2.getItemPos(0);
                    List<PickSelectEntity> cate2 = categoryData.get(firPos).getChildren().get(itemPos).getChildren();
                    if (cate2 != null && cate2.size() > 0) {
                        children.addAll(cate2);
                    }
                    mLeftDialog2.clearOtherDataInfo(entity.getSort());
                    mLeftDialog2.addEntity(PickCateType.TYPE_CATEGORY_2, children);
                    mLeftDialog2.showDialog();
                    break;
                case PickCateType.TYPE_PROVINCE:
                    viewModel.getCityData(entity.getItemNo(itemPos));
                    break;
                default:
                    break;
            }
        } else {
            if (entity.getSort() == PickCateType.TYPE_CATEGORY_0 || entity.getSort() == PickCateType.TYPE_CATEGORY_1 || entity.getSort() == PickCateType.TYPE_PROVINCE) {
                mLeftDialog2.clearOtherDataInfo(entity.getSort());
                mLeftDialog2.showDialog();
            }
        }
    }

    @Override
    public void loadData(SparseArray<PickSelectTextEntity> data, SparseIntArray map) {
        mData = PickCopyUtils.deepCopy(data);
        mFilters = map.clone();
        for (int i = 0; i < mData.size(); i++) {
            int key = mData.keyAt(i);
            PickSelectTextEntity entity = mData.get(key);
            updateChooseStatus(entity.getSort(), mFilters.get(entity.getSort()));
        }
        initFilterData(false);
    }

    @Override
    public void reset() {
        mFilters.clear();
        projectNo = "";
        projectName = "";
        priceNo = "";
        timeNo = "";
        areaName = "";
        pickResultCity.clear();
        pickResultTenderMethod.clear();
        pickResultProvince.clear();
        pickResultProject1.clear();
        pickResultProject2.clear();
        pickResultProject3.clear();
        clearOtherDataInfo(PickCateType.TYPE_CATEGORY_0);
        clearOtherDataInfo(PickCateType.TYPE_PROVINCE);
        loadData(mData, mFilters);
        mLeftDialog2.initData(mData, mFilters);
        mLeftDialog2.dismiss();
    }

    @Override
    public void onCancel() {
        mLeftDialog2.initData(mData, mFilters);
    }

    /**
     * 清理关联项为空
     */
    private void clearOtherDataInfo(int sort) {
        switch (sort) {
            case PickCateType.TYPE_CATEGORY_0:
                addEntity(PickCateType.TYPE_CATEGORY_1, new ArrayList<>());
                addEntity(PickCateType.TYPE_CATEGORY_2, new ArrayList<>());
                break;
            case PickCateType.TYPE_CATEGORY_1:
                addEntity(PickCateType.TYPE_CATEGORY_2, new ArrayList<>());
                break;
            case PickCateType.TYPE_PROVINCE:
                addEntity(PickCateType.TYPE_CITY, new ArrayList<>());
                break;
        }
    }

    public void addEntity(int index, List<PickSelectEntity> list) {
        if (mData.get(index) != null) {
            if (list == null || list.size() == 0) {
                mData.get(index).setPickSelectEntityList(new ArrayList<>());
            } else {
                mData.get(index).setPickSelectEntityList(list);
            }
        } else {
            mData.put(index, new PickSelectTextEntity(index, nameArray.get(index), list));
        }
        mFilters.put(index, 0);
    }

    public void setTenderGoodsCategoryAllList(List<PickSelectEntity<List<PickSelectEntity<List<PickSelectEntity>>>>> data) {
        categoryData.clear();
        categoryData.addAll(data);
        if (categoryData.size() != 0) {
            categoryData.get(0).setCheck(true);
            List<PickSelectEntity> list = new ArrayList<>(categoryData);
            refreshDataInfo(PickCateType.TYPE_CATEGORY_0, list);
        }
    }

    public void setTimeData(List<PickSelectEntity> data) {
        refreshDataInfo(PickCateType.TYPE_SIGN_TIME, data);
    }

    public void setPriceData(List<PickSelectEntity> data) {
        refreshDataInfo(PickCateType.TYPE_MONEY, data);
    }

    public void setTenderTypeData(List<PickSelectEntity> data) {
        refreshDataInfo(PickCateType.TYPE_SIGN, data);
    }

    public void setProvinceData(List<PickSelectEntity> data) {
        refreshDataInfo(PickCateType.TYPE_PROVINCE, data);
    }

    public void setCityData(List<PickSelectEntity> data) {
        mLeftDialog2.addEntity(PickCateType.TYPE_CITY, data);
        mLeftDialog2.showDialog();
    }

    private void updateChooseStatus(int key, int value) {
        mFilters.put(key, value);
        String no = mData.get(key).getItemNo(value);
        String name = mData.get(key).getItemName(value);
        switch (key) {
            case PickCateType.TYPE_CATEGORY_0:
                //类别
                if (TextUtils.isEmpty(no)) {
                    projectNo = no;
                    projectName = "工程分类";
                }else {
                    projectNo = no;
                    projectName = name;
                }
                break;
            case PickCateType.TYPE_CATEGORY_1:
            case PickCateType.TYPE_CATEGORY_2:
                if (!TextUtils.isEmpty(no)) {
                    projectNo = no;
                    projectName = name;
                }
                break;
            case PickCateType.TYPE_SIGN:
                // 报名方式
                pickResultTenderMethod.setName(name);
                pickResultTenderMethod.setNo(no);
                if (TextUtils.isEmpty(no)) {
                    return;
                }
                break;
            case PickCateType.TYPE_MONEY:
                // 概算金额
                priceNo = no;
                break;
            case PickCateType.TYPE_SIGN_TIME:
                // 报名结束时间
                timeNo = no;
                break;
            case PickCateType.TYPE_PROVINCE:
                // 省
                if (TextUtils.isEmpty(no)) {
                    pickResultProvince.setNo(no);
                    pickResultProvince.setName("所在地区");
                    areaName = "所在地区";
                } else {
                    pickResultProvince.setNo(no);
                    pickResultProvince.setName(name);
                    areaName = name;
                }
                break;
            case PickCateType.TYPE_CITY:
                // 城市
                if (!TextUtils.isEmpty(no)) {
                    pickResultCity.setNo(no);
                    pickResultCity.setName(name);
                    areaName = name;
                }
                break;
        }
    }

    public void getUrl(String url, String id) {
        WebViewX5HostActivity.start(getActivity(), url, id);
    }
}
